package com.vim.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.vim.common.model.base.DataSourceSetting;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import java.sql.SQLException;

/**
 * Mybatis配置
 */
@Configuration
@MapperScan(basePackages = "com.vim.modules.web.dao")
public class MybatisConfig {

    @Autowired
    private DataSourceSetting dataSourceSetting;

    /**
     * 连接池
     */
    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dataSourceSetting.getDriverClassName());
        dataSource.setUrl(dataSourceSetting.getUrl());
        dataSource.setUsername(dataSourceSetting.getUsername());
        dataSource.setPassword(dataSourceSetting.getPassword());

        //初始化大小，最小，最大
        dataSource.setInitialSize(dataSourceSetting.getInitialSize());
        dataSource.setMinIdle(dataSourceSetting.getMinIdle());
        dataSource.setMaxActive(dataSourceSetting.getMaxActive());
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(dataSourceSetting.getMaxWait());
        //配置监控统计拦截的filters，去掉后监控界面sql无法统计，'wall'用于防火墙
        try {
            dataSource.setFilters(dataSourceSetting.getFilters());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    /**
     * 事务管理
     * @return
     */
    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    /**
     * 连接池工厂
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setTypeAliasesPackage("com.vim.modules.web.model");
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        return sessionFactory;
    }
}
